<template>
  <el-dialog
    width="500px"
    :title="{ add: '新增角色', edit: '编辑角色' }[mode]"
    :visible="show"
    @close="closeEvent"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="form.description" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="closeEvent">取消</el-button>
        <el-button type="primary" @click="addRole">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { addRole, editRole } from '@/api/setting'
export default {
  props: ['show'],
  data() {
    return {
      mode: 'add',
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'blur' },
          { min: 1, max: 10, message: '请输入1~10个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '必填', trigger: 'blur' },
          { min: 1, max: 10, message: '请输入1~10个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭弹窗
    closeEvent() {
      this.$emit('update:show', false)
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 新增角色
    addRole() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          if (this.mode === 'add') {
            await addRole(this.form)
            this.$message.success('新增角色成功!')
          } else if (this.mode === 'edit') {
            await editRole(this.form)
            this.$message.success('编辑角色成功!')
          }
          this.closeEvent()
          this.$parent.getRole()
        } else {
          console.log('验证失败!')
        }
      })
    }
  }
}
</script>

<style></style>
